import sys
import platform
import atexit
from PyQt5.QtWidgets import QApplication
from app.server import Server
from app.utils.config_loader import app_config
from app.serial_manager import SerialManager
from app.main_window import MainWindow
from app.utils.logger import ETCLogger

# 初始化日志记录器
logger = ETCLogger()

def check_and_open_ports(serial_manager):
    """
    Check device connection and open serial ports
    :param serial_manager: SerialManager instance
    """
    os_type = "windows" if platform.system() == "Windows" else "linux"
    ports = app_config.get(f"serial_ports.{os_type}")
    baud_rates = app_config.get("baud_rates")

    for device, port in ports.items():
        baudrate = baud_rates.get(device)
        if serial_manager.is_port_available(port):
            if serial_manager.open_port(port, baudrate):
                logger.info(f"Successfully opened {device} serial port: {port}, baudrate: {baudrate}")
            else:
                logger.error(f"Failed to open {device} serial port: {port}")
        else:
            logger.warning(f"{device} device not connected: {port}")

def close_all_ports(serial_manager):
    """
    Close all serial ports
    :param serial_manager: SerialManager instance
    """
    logger.info("Closing all serial ports...")
    serial_manager.close_all_ports()

def main():
    # Initialize application
    app = QApplication(sys.argv)

    # Initialize serial manager
    serial_manager = SerialManager()

    # Check device connection and open serial ports
    check_and_open_ports(serial_manager)

    # Start reconnection thread
    serial_manager.start_reconnect_thread()

    # Register cleanup function on exit
    atexit.register(close_all_ports, serial_manager)
    atexit.register(serial_manager.stop_reconnect_thread)

    # Initialize TCP/IP server
    server = Server(
        host=app_config.get("server.host", "0.0.0.0"),
        port=app_config.get("server.port", 5555),
        max_clients=app_config.get("server.max_clients", 10),
        serial_manager=serial_manager
    )

    # Create and show main window
    main_window = MainWindow(server)
    main_window.show()

    # Run application
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()